package yto.freemarker.springbootstudy.jsonwebtoken;

import com.google.common.collect.Maps;
import io.jsonwebtoken.*;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 用于Java和Android的JWT token的生成和验证
 * <p>
 * jjwt的依赖和方式
 *
 * @author dongxing
 * @create 2018-06-01 9:51
 **/
public class JjwtTokenUtils {


    //公共的秘钥，保存在服务器端
    private final static String SECRET = "SHANGHAIYTO";


    /**
     * 加密Token
     *
     * @param claims
     * @return
     */
    public static String generateToken(Map<String, Object> claims) {

        //签发日期
        Date date = new Date();

        //过期时间
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 1);
        Date expiresDate = nowTime.getTime();

        return Jwts.builder()
                .setIssuedAt(date)
                .setClaims(claims)
                .setExpiration(expiresDate)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();

    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     */
    public static Claims getClaimsFromToken(String token) {

        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
            throw new RuntimeException("凭证已经过期，请重新获取！");
        }
        return claims;
    }


    public static void main(String[] args) {

        Map<String, Object> map = Maps.newHashMap();
        map.put("name", "张三");
        map.put("age", 24);
        map.put("city", "上海");

        String token = JjwtTokenUtils.generateToken(map);
        System.out.println("token:" + token);


        //Token
        String token1 = "eyJhbGciOiJIUzI1NiJ9.eyJjaXR5Ijoi5LiK5rW3IiwibmFtZSI6IuW8oOS4iSIsImV4cCI6MTUyNzgxODc4OSwiYWdlIjoyNH0.dEIyZHLXEOr9XbV6fartJZ2Xdy0mBaeu8zIqmbkwFOE";
        Claims claims = JjwtTokenUtils.getClaimsFromToken(token1);

        System.out.println(claims.get("name"));
        System.out.println(claims.get("age"));
        System.out.println(claims.get("city"));


    }


}
